import { Component, OnInit, ViewChild }          from '@angular/core';
import { ModalHelper, SettingsService }          from '@delon/theme';
import { STChange, STColumn, STComponent }       from '@delon/abc';
import { SFComponent, SFSchema, SFUISchemaItem } from '@delon/form';
import { City }                                  from "@shared/model/city";
import { map }                                   from "rxjs/operators";
import { of }                                    from "rxjs";
import { deviceStatus }                          from "../../manager/device";
import { Device, DeviceStatistics }              from "@shared/model/device-dto";
import { DeviceService }                         from "../../manager/device/device.service";
import { CacheService }                          from "@delon/cache";
import { ArrayService }                          from "@delon/util";
import { ManagerDeviceEditComponent }            from "../../manager/device/edit/edit.component";

@Component({
    selector   : 'app-device-list',
    templateUrl: './list.component.html',
})
export class DeviceListComponent implements OnInit
{
    url: string;
    private pid: string;
    searchSchema: SFSchema = {
        properties: {
            name    : {
                type : 'string',
                title: '设备名称',
            },
            province: {
                type : 'string',
                title: '省份',
            },
            city    : {
                type : 'string',
                title: '城市',
            },
        },
    };
    
    ui: SFUISchemaItem = {
        $province: {
            widget   : 'select',
            width    : 180,
            asyncData: () => this.cacheService.get<City[]>('kx/api/cities?level=0')
                .pipe(map(value => value.map(item => ({
                    value: item.id,
                    label: item.name,
                })))),
            validator: ( value, formProperty, form ) =>
            {
                this.pid = value;
                if ( value )
                {
                    form.searchProperty('/city').resetValue(null, false);
                }
            },
        },
        $city    : {
            widget   : 'select',
            width    : 180,
            asyncData: () =>
            {
                return this.pid ? this.cacheService.get<City[]>(`kx/api/cities?parentId=${ this.pid }`)
                    .pipe(map(value => value.map(i => ({
                        value: i.id,
                        label: i.name,
                    })))) : of([]);
            },
        },
    };
    
    @ViewChild('st', { static: true }) st: STComponent;
    @ViewChild('sf', { static: true }) sf: SFComponent;
    
    columns: STColumn[] = [
        { title: '编号', index: 'id', type: 'checkbox' },
        // { title: '设备ID', index: 'deviceId' },
        { title: '设备名称', index: 'deviceName' },
        // { title: '地址', index: 'address' },
        { title: '省份', index: 'address.province.name' },
        { title: '城市', index: 'address.city.name' },
        { title: '商家', index: 'storeName' },
        { title: '零售价', index: 'price', type: 'currency' },
        {
            title: '库存',
            index: 'stock',
            type : 'number',
            sort : { default: 'ascend', reName: { ascend: 'asc', descend: 'desc' } },
        },
        {
            title: '创建时间',
            type : 'date',
            index: 'createdDate',
            sort : { default: 'descend', reName: { ascend: 'asc', descend: 'desc' } },
        },
        { title: '最近在线', index: 'onlineDate', default: '-' },
        { title: 'ip地址', index: 'ipAddress', default: '-' },
        { title: '状态', index: 'status', type: 'badge', badge: deviceStatus, default: "UNACTIVE" },
        {
            title  : '操作',
            buttons: [
                {
                    text : '查看',
                    type : 'link',
                    icon : 'eye',
                    click: ( item: any ) => '/device/view/' + item.id,
                },
                {
                    text: '删除', icon: 'delete', type: 'del', click: ( item: any ) =>
                    {
                        this.deviceService.delete(item.id).subscribe(() =>
                        {
                            this.queryDeviceStatistics();
                            return this.st.reload();
                        });
                    },
                },
            ],
        },
    ];
    deviceStatistics: DeviceStatistics = new DeviceStatistics();
    selectedRows = [];
    // devices$: Observable<Array<Device>>;
    // isLoading$: Observable<boolean>;
    
    constructor( private modal: ModalHelper,
                 private deviceService: DeviceService,
                 private cacheService: CacheService,
                 private settingService: SettingsService,
                 private arrayService: ArrayService )
    {
        this.url = `${ deviceService.resourceUrl }/page`;
        // this.deviceStatistics = store.select(deviceStatistics).pipe(takeUntil(this.ngDestroy));
        // this.devices$         = store.select(device).pipe(takeUntil(this.ngDestroy));
        // this.isLoading$       = store.select(deviceLoading).pipe(takeUntil(this.ngDestroy));
    }
    
    ngOnInit()
    {
        this.queryDeviceStatistics();
        // this.store.dispatch(QueryDeviceStatistics());
        // this.store.dispatch(LoadDevicePage({
        //   size: this.st.ps,
        //   page: this.st.pi - 1,
        //   sort: [{ name: 'createdDate', asc: 'desc' }],
        // }));
    }
    
    private queryDeviceStatistics()
    {
        this.deviceService.queryDeviceStatistics().subscribe(value => this.deviceStatistics = value);
    }
    
    add()
    {
        this.modal
            .createStatic(ManagerDeviceEditComponent, { record: new Device() })
            .subscribe(() =>
            {
                this.queryDeviceStatistics();
                return this.st.reset();
            });
    }
    
    // onChanged(e: STChange) {
    //   console.log(e);
    //
    // }
    export()
    {
    
    }
    
    stOnChange( change: STChange )
    {
        switch (change.type)
        {
            case "pi":
                break;
            case "ps":
                break;
            case "checkbox":
                this.selectedRows = change.checkbox!;
                break;
            case "radio":
                break;
            case "sort":
                break;
            case "filter":
                break;
            case "click":
                break;
            case "dblClick":
                break;
            case "expand":
                break;
            
        }
    }
    
    updatePrice()
    {
    
    }
    
}
